# -*- coding:utf-8 -*-
from selenium import selenium, webdriver;
from selenium.common.exceptions import NoSuchElementException
import time, logging, ConfigParser, os
from multiprocessing import Process,freeze_support
import json,urllib2,urllib
from urllib2 import URLError
#import ocr
import test_join
import sys
from TiffImagePlugin import TiffImageFile
#from Tkinter import *
#import ImageTk

encoding = sys.stdin.encoding
print encoding

FORMAT = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('vote')
hdlr = logging.FileHandler('vote.log')
formatter = logging.Formatter(FORMAT)
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

VOTE_SUCCESS = -1
VOTE_ERROR = -2
WAIT_TIME=1800

class HttpBot:
    """an HttpBot represents one browser session, with cookies."""
    def __init__(self):
        cookie_handler= urllib2.HTTPCookieProcessor()
        self.cookie_handler = cookie_handler;
        redirect_handler= urllib2.HTTPRedirectHandler()
        self._opener = urllib2.build_opener(redirect_handler, cookie_handler)

    def GET(self, url):
        return self._opener.open(url).read()

    def POST(self, url, parameters):
        return self._opener.open(url, urllib.urlencode(parameters)).read()

def votes(user_name, password, obtainer_id):
    driver = webdriver.Firefox();
    wait_dt = None
    for i in range(1000):
        try:
            if i == 0 or wait_dt == VOTE_ERROR:
                wait_dt = do_vote(user_name, password, obtainer_id, True);
            elif wait_dt == VOTE_SUCCESS:
                wait_dt = WAIT_TIME;
            while wait_dt > 0:
                chat_room(driver, user_name, password, wait_dt);
                wait_dt = do_vote(user_name, password, obtainer_id, False);
        except (ValueError, URLError):
                wait_dt = VOTE_ERROR; 
        except NoSuchElementException as excep:
            logger.warning("something raised an exception: " + str(excep), exc_info=True)
            pass
    driver.quit();
    
def get_verify_image(bot):
    str_time = repr(time.time())
    str_time = str_time[:10] + str_time[11:]
    image_name = str(os.getpid()) + 'verify.png';
    image_file = open(image_name, 'wb')
    image_file.write(bot.GET('http://www.peng58.com//verify.jpg?width=95&height=30&' + str_time))
    image_file.close()
    return image_name

def get_auth_code(bot):
    auth_code = None
    while auth_code is None or auth_code == '':
        auth_code = test_join.get_ocr_value(test_join.get_verify_tif(get_verify_image(bot)))
    return auth_code.encode('utf-8')
#    image_name = get_verify_image(bot)
#    codes = []
#    root = Tk()
#    canvas = Canvas(root,width = 95, height = 35, bg = 'yellow')
#    canvas.pack(expand = YES, fill = BOTH)
#    gif1 =  ImageTk.PhotoImage(file = image_name)
#    canvas.create_image(0, 0, image = gif1, anchor = NW)
#    entry = Entry(root, width=10)
#    entry.pack(side=TOP,padx=10,pady=10)
#    entry.bind('<Return>', lambda event: display_auth_code(event, root, entry, codes))
#    root.mainloop()
#    os.remove(image_name)
#    return codes[0]

#def display_auth_code(event, root, entry, codes):
#    print entry.get().encode('utf-8', 'ignore')
#    codes.append(entry.get().encode('utf-8', 'ignore'))
#    root.destroy()

def do_vote(user_name, password, obtainer_id, ignore_log):
    bot = HttpBot();
    if login_main_page(bot, user_name, password):
        verify_fail = True
        while verify_fail:
            verify_fail = False
            auth_code = get_auth_code(bot)
            #logger.debug("auth code: %s" % auth_code)
            vote_result = json.loads(bot.POST('http://www.peng58.com/kalaok/?do=vote', {'auth_code': auth_code, 'obtainer_id' : obtainer_id, 'obtainer_area' : '123 ', 'obtainer_type': '1'}))
            logger.debug("vote result: %d" % vote_result['result'])
            if vote_result['result'] == 0:
                logger.info('============ %s vote success ============',  user_name)
                return VOTE_SUCCESS;
            elif vote_result['result'] == 1:
                wait_dt = get_wait(vote_result['wait_dt'])
                if wait_dt == 0:
                    wait_dt = WAIT_TIME
                else:
                    wait_dt = WAIT_TIME - wait_dt
                if not ignore_log:
                    logger.info('============ %s vote fail, should keep online %d second.' % (user_name, wait_dt))
                return wait_dt             
            elif vote_result['result'] == 1002:
                #logger.error('verify fail with code: %s', auth_code)
                verify_fail = True
            else:
                logger.error(' %s vote fail, message: %s ',  user_name, vote_result['result_desc'])
                return 0;
    else:
        return 0;

def get_wait(wait_dt):
    wait_dt = wait_dt[0:len(wait_dt)-1]
    if wait_dt[1].isdigit():
        return int(wait_dt[0:2]) * 60 + int(wait_dt[3:len(wait_dt)])
    else:
        return int(wait_dt[0]) * 60 + int(wait_dt[2:len(wait_dt)])

def logout(driver):
    driver.get("http://www.peng58.com/user/login.html?do=logout");
    time.sleep(5);
    
def chat_room(driver, user_name, password, wait_time):
    try:
        driver.find_element_by_id("sign_button")
    except NoSuchElementException:
        driver.get("http://www.peng58.com");
        time.sleep(5);
    driver.execute_script("$('.login_click').click()");
  
    driver.execute_script("$('#user_input').val(" + "'" + user_name + "')");
    driver.execute_script("$('#pwd_input').val(" + "'" + password + "')");
    driver.find_element_by_id("pwd_input").submit();
    logger.debug('%s enter chat room with wait time %d', user_name, wait_time)
    time.sleep(20);
    time.sleep(wait_time);
    logout(driver)

def login_main_page(bot, user_name, password):
    login_result= json.loads(bot.POST('http://www.peng58.com/service/json.php?do=user,login', {'password':password, 'value':user_name}))
    if login_result['result'] == 0:
        logger.debug('%s login success when vote.' % user_name);
        return True
    else:
        logger.error( '%s login failed when vote. pls check user name and password' % user_name);
        return False

if __name__ == '__main__':
    freeze_support()
    logger.debug('updated version 5')
    cf = ConfigParser.ConfigParser();
    cf.read("vote.cfg");
    obtainer_id = cf.get('vote_setting', 'obtainer_id')
    users = cf.items("vote_users");
    logger.info('users amount: %d', len(users));
    i = 0;
    for user in users:
        if i != 0:
            time.sleep(40);
        process = Process(target=votes, args=(user[0], user[1], obtainer_id));
        logger.debug('process launched')
        process.start();
        i = i + 1